package com.fate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fate.domain.Notice;
import com.fate.mapper.NoticeMapper;
import com.fate.service.NoticeService;
import com.fate.vo.NoticeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 分页查询公告
     *
     * @param page
     * @param notice
     * @return
     */
    @Override
    public Page<Notice> findNoticePage(Page<Notice> page, Notice notice) {
        return (Page<Notice>) noticeMapper.selectPage(page, new LambdaQueryWrapper<Notice>()
                .eq(!ObjectUtils.isEmpty(notice.getStatus()), Notice::getStatus, notice.getStatus())
                .eq(!ObjectUtils.isEmpty(notice.getIsTop()), Notice::getIsTop, notice.getIsTop())
                .like(StringUtils.hasText(notice.getTitle()), Notice::getTitle, notice.getTitle())
                .orderByDesc(Notice::getPublishTime)
        );
    }

    /**
     * 查询前台公告列表
     *
     * @return
     */
    @Override
    public List<NoticeVo> loadFrontNotice() {
        List<Notice> notices = noticeMapper.selectList(new LambdaQueryWrapper<Notice>()
                .eq(Notice::getIsTop, 1)
                .eq(Notice::getStatus, 1)
                .orderByDesc(Notice::getPublishTime)
        );
        List<NoticeVo> noticeVos = new ArrayList<>(notices.size() * 2);
        notices.forEach(notice -> {
            NoticeVo noticeVo = new NoticeVo();
            BeanUtil.copyProperties(notice, noticeVo, true);
            noticeVos.add(noticeVo);
        });
        return noticeVos;
    }
}